#!/usr/bin/evn python
# -*- coding: utf8 -*-
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import (ListView, DetailView, CreateView, UpdateView,DeleteView)
from contacts.models import Contact
from contacts.forms import (ContactForm, ContactAddressFormset)


class LoginRequiredMixin(object):
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)


class ContactListView(LoginRequiredMixin, ListView):
    model = Contact
    template_name = "contact_list.html"

    def get_queryset(self):
        return Contact.objects.filter(owner=self.request.user)

class ContactDetailView(LoginRequiredMixin, DetailView):
    model = Contact
    template_name = "contact_detail.html"

class ContactCreateView(LoginRequiredMixin, CreateView):
    model = Contact
    template_name = "contact_edit.html"
    form_class = ContactForm

    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super(ContactCreateView, self).form_valid(form)


class ContactEditView(LoginRequiredMixin, UpdateView):
    model = Contact
    template_name = "contact_edit.html"
    form_class = ContactForm


class ContactDeleteView(LoginRequiredMixin, DeleteView):
    model = Contact
    template_name = 'contact_confirm_delete.html'
    def get_success_url(self):
        return reverse('contact-list')

class ContactAddressEditView(LoginRequiredMixin, UpdateView):
    model = Contact
    template_name = 'contact_address_edit.html'
    form_class = ContactAddressFormset

    def get_success_url(self):
        return self.get_object().get_absolute_url()
